/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.pima.gestrest.business;

import com.pima.gestrest.model.Restaurant;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.faces.model.SelectItem;
import javax.persistence.*;

/**
 *
 * @author Pierre-Louis Conte
 */
@Stateless
public class RestaurantEJB {

    // ======================================
    // =             Attributes             =
    // ======================================
    @PersistenceContext(unitName = "jsfExamplePU")
    private EntityManager em;

    // ======================================
    // =           Public Methods           =
    // ======================================
    public List<Restaurant> findAll() {
        Query query = em.createNamedQuery(Restaurant.FIND_ALL);
        return query.getResultList();
    }

    public List<SelectItem> getItems () {
        ArrayList<SelectItem> items = new ArrayList<SelectItem>();

        Query query = em.createNamedQuery(Restaurant.FIND_ALL);
        for(Restaurant restaurant : (List<Restaurant>)query.getResultList())
            items.add(new SelectItem(restaurant, restaurant.getId()+ " - " + restaurant.getTitle()+" - "+restaurant.getVille().getTitle()));

        return items;
    }

    public Restaurant create(Restaurant restaurant) {
        em.persist(restaurant);
        return restaurant;
    }

    public Restaurant update(Restaurant restaurant) {
        return em.merge(restaurant);
    }

    public void delete(List<Restaurant> list) {
        for (Restaurant restaurant : list) {
            delete(restaurant);
        }
    }

    public void delete(Restaurant restaurant) {
        em.remove(em.merge(restaurant));
    }
}
